﻿var links = '';
// http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
var fmtdict = new Array();
fmtdict['18'] = '360p MP4';
fmtdict['22'] = '720p MP4';
fmtdict['37'] = '1080p MP4';
fmtdict['38'] = '4K MP4';
fmtdict['5'] = '240p FLV';
fmtdict['34'] = '360p FLV';
fmtdict['35'] = '480p FLV';
fmtdict['43'] = '360p WebM';
fmtdict['44'] = '480p WebM';
fmtdict['45'] = '720p WebM';
fmtdict['46'] = '1080p WebM';
fmtdict['17'] = '144p 3GP';
fmtdict['36'] = '240p 3GP';
fmtdict['82'] = '3D 360p MP4';
fmtdict['84'] = '3D 720p MP4';
fmtdict['85'] = '3D 1080p MP4';
fmtdict['100'] = '3D 360p WebM';
fmtdict['101'] = '3D 480p WebM';
fmtdict['102'] = '3D 720p WebM';
fmtdict['103'] = '3D 1080p WebM';

var title = document.getElementsByName('title').item(0).content.replace('/','');
// console.log(title);
var urls = document.body.textContent.match(/"url_encoded_fmt_stream_map": "([^"]*)"/)[1];
urls = urls.replace(/\\u0026/g,'&').split(',');
// urls is now array ["itag=37&url=http...","itag=22&.."...]
var vurl = '';
var vfmt = '';
for(var i=0;i<urls.length;i++){
  vfmt = urls[i].match(/itag=(\d+)/)[1];
  vurl = urls[i].match(/url=(.*)/)[1];
  // vurl is http..., correct sig name, encode " to avoid problem
  vurl = unescape(vurl).replace(/sig=/,'signature=').replace(/"/g,'%22');
  //console.log(i+':'+vurl);
  links += '<a href="' +vurl+ '&title=' +title+ '">[' +fmtdict[vfmt]+ ']--</a>';
}

var dlb = document.getElementById('my-download-links');
if(!dlb){
    dlb = document.createElement('div');
    dlb.setAttribute('id', 'my-download-links');
    dlb.style.width = "640px";
}
dlb.innerHTML = links;
try{
    document.getElementById('watch-video').appendChild(dlb);
}
catch(err){
  try{
    document.getElementsByClassName('module-view featured-video-view-module')[0].appendChild(dlb);
  }
  catch(err){
    console.log(err.message)
  }
}
